<?php

namespace App\Models;

use App\Enums\RegistryFileType;
use App\Enums\RegistryStatus;
use App\Enums\SettleWay;
use BenSampo\Enum\Traits\CastsEnums;

/**
 * @mixin IdeHelperRegistry
 */
class Registry extends BaseModel
{
    use CastsEnums;

    protected $casts = [
        'status' => RegistryStatus::class,
        'settle_way' => SettleWay::class,
    ];

    protected $appends = [
        'cert_images',
        'display_pay_amount',
    ];

    public function agent()
    {
        return $this->belongsTo(Agent::class);
    }

    public function user()
    {
        return $this->belongsTo(FrontendUser::class);
    }

    public function order()
    {
        return $this->hasOne(RegistryOrder::class);
    }

    public function authors()
    {
        return $this->belongsToMany(RegistryAuth::class, 'registry_authors');
    }

    public function owners()
    {
        return $this->belongsToMany(RegistryAuth::class, 'registry_owners');
    }

    public function productFiles()
    {
        return $this->hasMany(RegistryFile::class)->where('file_type', RegistryFileType::PRODUCT_FILE);
    }

    public function productImages()
    {
        return $this->hasMany(RegistryFile::class)->where('file_type', RegistryFileType::PRODUCT_IMAGE);
    }

    public function attachFiles()
    {
        return $this->hasMany(RegistryFile::class)->where('file_type', RegistryFileType::PRODUCT_ENCLOSURE);
    }

    public function auditHistories()
    {
        return $this->hasMany(RegistryAuditHistory::class)->orderBy('id');
    }

    public function getCertImagesAttribute()
    {
        return array_filter(explode(',', $this->cert_image_urls));
    }

    public function getDisplayPayAmountAttribute()
    {
        return toYuan($this->pay_amount);
    }
}
